package com.self.admin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.self.common.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @version v1.0
 * @ClassName: FileController
 * @Description:
 * @Author: Mac
 * @Date: 2022/6/5 15:11
 */
@Slf4j
@RestController
@Api(tags = "文件上传")
public class FileController {

    @Autowired
    private OSS ossClient;

    @Value("${oss.bucket:exchange-imgs}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endPoint;

    @Autowired
    private Snowflake snowflake;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessKey;

    @Value("${oss.callbackUrl:http://xxx/image/callback}")
    private String callbackUrl;


    @PostMapping("/image/AliYunImgUpload")
    @ApiOperation(value = "文件上传")
    public R<String> fileUpload(@RequestParam("file") MultipartFile file)throws IOException {
        String filePath = DateUtil.today().replaceAll("-","/")+"/"+snowflake.nextIdStr()+"."+FileUtil.extName(file.getOriginalFilename());
        ossClient.putObject(bucket,filePath,file.getInputStream());
        return R.ok("https://" + bucket+ "."+ endPoint +"/"+ filePath);
    }

    @GetMapping("/image/pre/upload")
    @ApiOperation(value = "获取一个上传的票据")
    public R<Object> asyncUpload() {
        String dir = DateUtil.today().replaceAll("-", "/")+"/";
        Map<String, String> uploadPolicy = getUploadPolicy(30L,5*1024*1024L,dir);
        return R.ok(uploadPolicy);
    }

    /**
     * 获取上传的票据
     *
     * @param expireTime  票据的过期时间
     * @param dir         文件上传的文件夹
     * @param maxFileSize 上传文件的最大体积
     * @param callbackUrl 前端把文件上传成功后的回调地址
     * @return 票据
     */
    private Map<String, String> getUploadPolicy(Long expireTime, Long maxFileSize, String dir) {
        // 返回给前端的值
        Map<String, String> respMap = new LinkedHashMap<>();
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime); // 过期时间
        // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
        PolicyConditions policyConds = new PolicyConditions();
        // 设置上传的大小 ,最大为3M
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxFileSize);
        // 上传的到那个文件夹
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        try {
            // 生成一个票据
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);

            // 对票据加密
            byte[] binaryData = postPolicy.getBytes("utf-8");

            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap.put("accessid", accessKey);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", "https://" + bucket + "." + endPoint); // host的格式为 https://bucketname.endpoint
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("callbackUrl",callbackUrl);
            jsonObject.put("callbackBody","filename=${object}&size=${size}&mimeType=${mimeType}" +
                    "&height=${imageInfo.height}&width=${imageInfo.width}");
            jsonObject.put("callbackBodyType", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
            String callbackBinary = BinaryUtil.toBase64String(jsonObject.toString().getBytes());
            respMap.put("callback", callbackBinary); // 前端上传成功了,可以使用该地址来通知后端.
        } catch (UnsupportedEncodingException e) {
            log.error("上传文件异常:{}",e);
        }
        return respMap;
    }
}
